package com.rodteixo.Replicador;

import java.io.*;
import java.util.Properties;
import java.util.ArrayList;
import javax.mail.*;
import javax.mail.internet.*;
import com.sun.mail.pop3.*;
import javax.mail.internet.MimeMessage;
import java.sql.*;

public class ReplicadorEmail {

	private Session session;
    private Properties pop3Props;
    private Store store;
    private Folder folder;
    private ArrayList mailToConnect;
    private String smtpEnvio;
    private String smtpPort;
    private String email;
    private String nomeConexao;
    private String senhaEmail;
    
	public static void main (String args[]) throws Exception {
		ReplicadorEmail remail = new ReplicadorEmail();
		remail.transferMails();
    }

	public ReplicadorEmail() {

		RemoteConection cnx = new RemoteConection("Replica1", "", "");

		ResultSet emailOrigem = cnx.getConsulta("Select * from [EmailLeitura];");
		
		mailToConnect = new ArrayList(0);
		
		try {
			if (emailOrigem.next()) {
				nomeConexao = emailOrigem.getString("NomeConexao");
				senhaEmail = emailOrigem.getString("Senha");
				email = emailOrigem.getString("Email");
				mailToConnect.add(new String[]{email, nomeConexao, emailOrigem.getString("Usuario"), emailOrigem.getString("POP"), emailOrigem.getString("POPPort")});
				smtpEnvio = emailOrigem.getString("smtp");
				smtpPort = emailOrigem.getString("stmpPort");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void transferMails() {
		for (int i = 0; i < mailToConnect.size(); i++) {
			connectToMail((String[])mailToConnect.get(i));
			filtraMensagens();
			closeMail();
		}
	}
	
	private void connectToMail(String[] param) {
		// Store store = new POP3SSLStore(session, new URLName("pop3", "pop.gmail.com", 995, "", "duelpass", "rodt2000"));
		pop3Props = new Properties();
	    
	    pop3Props.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
	    pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
	    pop3Props.setProperty("mail.pop3.port",  param[4]);
	    pop3Props.setProperty("mail.pop3.socketFactory.port", param[4]);
	    
	    session = Session.getInstance(pop3Props, null);
		System.out.println("Conectando a " + param[0] + " ...");
	    store = new POP3SSLStore(session, new URLName("pop3", param[3], Integer.parseInt(param[4]), "", param[1], param[2]));
	    try {
	    	store.connect();
	    	folder = store.getFolder("INBOX");
	        // Open read-only
	    	folder.open(Folder.READ_WRITE);
	    	System.out.println("Conectado ao INBOX - OK");
	    } catch(MessagingException e) {
	    	e.printStackTrace();
	    }
	}
	
	private void closeMail() {
		try {
			folder.close(true);
			store.close();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}
	
	private void filtraMensagens() {

		System.out.println("lendo as mensagens de origem...");
		try {
			Message[] message = folder.getMessages();

			for (int i = 0; i < message.length; i++) {
				System.out.println("Mensagem: " + i);
				System.out.println(i + " - " + message[i].getSubject());
				String assunto = message[i].getSubject();
				boolean mailProcessado = false;
				// encaminhar mensagem
				mailProcessado = encaminhaEmail (message[i], "", "");
			}
	    } catch (MessagingException e) {
	    	e.printStackTrace();
	    }
	}
	
	private boolean encaminhaEmail (Message msg, String addSubject, String addText) {
		System.out.println("Encaminhando mensagem...");
	    // Get system properties
	    
		boolean encOK = false;
		
	    Properties props = System.getProperties();
		
	    // Setup mail server
	    props.put("mail.transport.protocol","smtp"); // diz que utilizarei um protocolo de seguran&#65533;a  
	    props.put("mail.smtp.starttls.enable","true"); // diz que utilizarei o protocolo de seguran&#65533;a TLS  
	    props.put("mail.smtp.host",smtpEnvio); // diz que o servidor que estou mandando &#65533; o gmail  
	    //props.put("mail.smtp.host","smtp.mail.yahoo.com.br"); // diz que o servidor que estou mandando &#65533; o gmail
	    props.put("mail.smtp.auth","true"); // diz que &#65533; necess&#65533;rio uma autentica&#65533;&#65533;o  
	    props.put("mail.smtp.user", nomeConexao);  
	    //props.put("mail.smtp.user", "duelpass_online");
	    props.put("mail.debug", "true");  
	    props.put("mail.smtp.port", smtpPort);  
	    props.put("mail.smtp.debug", "true");  
	    props.put("mail.mime.charset", "ISO-8859-1");  
	    props.put("mail.smtp.socketFactory.port", smtpPort);  
	    props.put("mail.smtp.socketFactory.fallback", "false");  
	    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");  

	    // Get session
	    Authenticator auth = new Autenticacao(nomeConexao, senhaEmail);
	    Session session = Session.getInstance(props, auth);

	    // Create the message to forward
    	Message forward = new MimeMessage(session);

	    try {

	    	// Fill in header
	    	forward.setSubject("ENC: " + addSubject + msg.getSubject());
	    	forward.setFrom(new InternetAddress(email));
	    	//forward.setFrom(new InternetAddress("duelpass_online@yahoo.com.br"));
	    	
	    	
	    	forward.addRecipient(Message.RecipientType.TO, new InternetAddress("rodteixo2@yahoo.com.br"));

	    	// Create your new message part
	    	BodyPart messageBodyPart = new MimeBodyPart();
	    	String msgBodyText = "Mensagem Original:\n\nEnviada por: ";

	    	for (int i = 0; i < msg.getFrom().length; i++) {
	    		msgBodyText = msgBodyText + "\n" + msg.getFrom()[i].toString();
	    	}
	    	msgBodyText = msgBodyText + "\n\nDestino Original: ";
	    	for (int i = 0; i < msg.getFrom().length; i++) {
	    		msgBodyText = msgBodyText + "\n" + msg.getAllRecipients()[i].toString();
	    	}
	    	if (msg.getSentDate() != null) {
		    	msgBodyText = msgBodyText + "\n\nData de Envio: " + msg.getSentDate().toString();	    		
	    	}
	    	if (msg.getReceivedDate() != null) {
	    		msgBodyText = msgBodyText + "\nData de Recebimento: " + msg.getReceivedDate().toString();
	    	}
	    	msgBodyText = msgBodyText + "\n\n" + addText;
	    	messageBodyPart.setText(msgBodyText);

	    	// Create a multi-part to combine the parts
	    	Multipart multipart = new MimeMultipart();
	    	multipart.addBodyPart(messageBodyPart);

	    	// Create and fill part for the forwarded content
	    	messageBodyPart = new MimeBodyPart();
	    	messageBodyPart.setDataHandler(msg.getDataHandler());

	    	// Add part to multi part
	    	multipart.addBodyPart(messageBodyPart);

	    	// Associate multi-part with message
	    	forward.setContent(multipart);

	        // Send message
	        //SMTPSSLTransport transport = new SMTPSSLTransport(session, new URLName("smpt", "smtp.gmail.com", 995, "", "duelpass", "rodt2000"));
	        Transport transport = session.getTransport("smtp");

	        System.out.println("\n\nTentando connectar ao SMTP server...");
	    	transport.connect();
	    	System.out.println("\n\nConectado ao servidor SMTP - OK");
	        
	        //msg.saveChanges();
	    	transport.sendMessage(forward, new Address[]{new InternetAddress("rodteixo2@yahoo.com.br")});
	        
	        System.out.println("Mensagem enviada com sucesso - OK");
	        encOK = true;

	    } catch (MessagingException e) {
	    	e.printStackTrace();
	    }
	    return encOK;
	}
}
